package com.tyx.chargingpile.service.impl;

import com.tyx.chargingpile.Enum.ServiceMessageEume;
import com.tyx.chargingpile.cache.SocketChannelMap;
import com.tyx.chargingpile.service.ChargingPileService;
import com.tyx.chargingpile.service.MessageService;
import com.tyx.chargingpile.util.Util;
import com.tyx.chargingpile.vo.SocketResponseResult;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 充电桩停止充电下行
 */
@Service("chargingPileCloseDown")
public class ChargingPileCloseDown implements ChargingPileService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ChargingPileCloseDown.class);

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, byte[] context) throws Exception {
        return null;
    }

    @Override
    public SocketResponseResult execute(ChannelHandlerContext channelHandlerContext, Map data) throws Exception {
        Map<String,String> dwn = new HashMap<>();
        String pileNum = (String) data.get("PileId"); // 桩编号
        String gunpointNum = (String) data.get("ChargePortIndex"); //枪号
        String orderNum = (String) data.get("Orderid"); // 订单编号
        String powerType = SocketChannelMap.getPileInfo(pileNum).getPowerType();

        pileNum = Util.FronFillZero(pileNum,12);
        gunpointNum = Util.FronFillZero(gunpointNum,2);
        powerType = Util.FronFillZero(powerType,2);

        // 组装下发报文
        dwn.put("gunpointNum",gunpointNum);
        dwn.put("powerType",powerType);
        dwn.put("pileNum",pileNum);
        dwn.put("orderNum",orderNum);
        byte[] dwnContext = MessageService.getMessage(dwn, ServiceMessageEume.STOP.getDwnLinePath());
        ByteBuf pingMessage = Unpooled.buffer();
        pingMessage.writeBytes(dwnContext);
        channelHandlerContext.writeAndFlush(pingMessage);
        String commandId = ServiceMessageEume.STOP.getCode();
//        LOGGER.info("前置下发电桩停止充电：" + Util.BCD2String(dwnContext));
        LOGGER.info("客户端"+channelHandlerContext.channel().id().toString()+",指令控制编号："+commandId+",桩编号:" + pileNum + ",前置下发电桩停止充电下行报文" + Util.BCD2String(dwnContext));
        return new SocketResponseResult(channelHandlerContext,dwnContext);
    }
}
